package com.yinhe.music.yhmusic.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.yinhe.music.yhmusic.db.bean.DownloadMusicEntity;
import com.yinhe.music.yhmusic.db.bean.MenuDBEntity;
import com.yinhe.music.yhmusic.db.bean.PlayListDBEntity;
import com.yinhe.music.yhmusic.db.bean.RecentMusicDBEntity;
import com.yinhe.music.yhmusic.db.bean.SongDBEntity;
import com.yinhe.music.yhmusic.db.dao.DownloadMusicEntityDAO;
import com.yinhe.music.yhmusic.db.dao.MenuEntityDAO;
import com.yinhe.music.yhmusic.db.dao.PlayListEntityDAO;
import com.yinhe.music.yhmusic.db.dao.RecentSongEntityDAO;
import com.yinhe.music.yhmusic.db.dao.SongEntityDAO;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.model.Music;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by Johnson on 2017/10/19.
 */

public class DataBaseAccessor {

    private static DataBaseAccessor g_Instance = null;
    // version:1.5.0
    // private static final int CORE_DB_VERSION = 6;
    // version:1.6.0
    // private static final int CORE_DB_VERSION = 7;
    // version:2.0.
    // private static final int CORE_DB_VERSION = 9;
    // version:2.1.2
    private static final int CORE_DB_VERSION = 10;

    private DownloadMusicEntityDAO mDownloadMusicDao;
    private MenuEntityDAO mMenuDao;
    private PlayListEntityDAO mPlayListDao;
    private RecentSongEntityDAO mRecentSongDao;
    private SongEntityDAO mSongDao;

    private DbHelper mDBHelper;

    public static synchronized DataBaseAccessor getInstance() {
        if (g_Instance == null) {
            g_Instance = new DataBaseAccessor();
        }

        return g_Instance;
    }

    public void initDBHelper(Context context, String dbName) {

        if (mDBHelper == null) {
            mDBHelper = new DbHelper(context, dbName, CORE_DB_VERSION) {

                @Override
                protected void onDbUpgrade(SQLiteDatabase database,
                                           ConnectionSource connectionSource, int oldVersion, int newVersion)
                        throws SQLException {
                    if (oldVersion == 1) {
                        // TableUtils.dropTable(connectionSource,DownloadDBEntity.class,true);
                        // TableUtils.createTable(connectionSource, DownloadDBEntity.class);
                        TableUtils.dropTable(connectionSource, SongDBEntity.class, true);
                        TableUtils.createTable(connectionSource, SongDBEntity.class);
                        TableUtils.dropTable(connectionSource, RecentMusicDBEntity.class, true);
                        TableUtils.createTable(connectionSource, RecentMusicDBEntity.class);
                        TableUtils.dropTable(connectionSource, DownloadMusicEntity.class, true);
                        TableUtils.createTable(connectionSource, DownloadMusicEntity.class);
                        TableUtils.dropTable(connectionSource, PlayListDBEntity.class, true);
                        TableUtils.createTable(connectionSource, PlayListDBEntity.class);
                        TableUtils.dropTable(connectionSource, MenuDBEntity.class, true);
                        TableUtils.createTable(connectionSource, MenuDBEntity.class);
                    }

                    if (oldVersion == 3) {
                        try {
                            TableUtils.dropTable(connectionSource, MenuDBEntity.class, true);
                            TableUtils.createTable(connectionSource, MenuDBEntity.class);
                            // String sql = "ALTER TABLE MenuDBEntity ADD COLUMN editable INT default 1";
                            String sql2 = "ALTER TABLE RecentMusicDBEntity ADD COLUMN is_radio BOOLEAN default flase";
                            String sql3 = "ALTER TABLE SongDBEntity ADD COLUMN is_radio BOOLEAN default false";
                            String sql4 = "ALTER TABLE PlayListDBEntity ADD COLUMN is_radio BOOLEAN default false";
                            database.execSQL(sql2);
                            database.execSQL(sql3);
                            database.execSQL(sql4);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (oldVersion < 6) {
                        try {
                            String sql2 = "ALTER TABLE RecentMusicDBEntity ADD COLUMN radio_id int default 0";
                            database.execSQL(sql2);

                            sql2 = "ALTER TABLE SongDBEntity ADD COLUMN radio_id int default 0";
                            database.execSQL(sql2);

                            sql2 = "ALTER TABLE DownloadMusicEntity ADD COLUMN radio_id int default 0";
                            database.execSQL(sql2);

                            TableUtils.dropTable(connectionSource, PlayListDBEntity.class, true);
                            TableUtils.createTable(connectionSource, PlayListDBEntity.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (oldVersion < 7) {
                        try {
                            String sql2 = "ALTER TABLE RecentMusicDBEntity ADD COLUMN lyrics_code string default 'utf-8'";
                            database.execSQL(sql2);

                            sql2 = "ALTER TABLE SongDBEntity ADD COLUMN lyrics_code string default 'utf-8'";
                            database.execSQL(sql2);

                            sql2 = "ALTER TABLE DownloadMusicEntity ADD COLUMN lyrics_code string default 'utf-8'";
                            database.execSQL(sql2);
                            sql2 = "ALTER TABLE PlayListDBEntity ADD COLUMN lyrics_code string default 'utf-8'";
                            database.execSQL(sql2);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (oldVersion < 9) {
                        try {
                            String sql2 = "ALTER TABLE MenuDBEntity ADD COLUMN lang int default 0";
                            database.execSQL(sql2);
                            sql2 = "ALTER TABLE MenuDBEntity ADD COLUMN detail string default ''";
                            database.execSQL(sql2);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (oldVersion < 10) {
                        try {
                            String sql2 = "ALTER TABLE SongDBEntity ADD COLUMN sysmusiclang int default -1";
                            database.execSQL(sql2);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                protected void onDbCreate(SQLiteDatabase database,
                                          ConnectionSource connectionSource) throws SQLException {
                    // TableUtils.createTable(connectionSource, DownloadDBEntity.class);
                    TableUtils.createTable(connectionSource, SongDBEntity.class);
                    TableUtils.createTable(connectionSource, RecentMusicDBEntity.class);
                    TableUtils.createTable(connectionSource, DownloadMusicEntity.class);
                    TableUtils.createTable(connectionSource, PlayListDBEntity.class);
                    TableUtils.createTable(connectionSource, MenuDBEntity.class);
                }

                @Override
                public void onOpen(SQLiteDatabase db) {

                }
            };

            try {
                mDownloadMusicDao = new DownloadMusicEntityDAO(mDBHelper);
                mMenuDao = new MenuEntityDAO(mDBHelper);
                mPlayListDao = new PlayListEntityDAO(mDBHelper);
                mRecentSongDao = new RecentSongEntityDAO(mDBHelper);
                mSongDao = new SongEntityDAO(mDBHelper);

                mDBHelper.getWritableDatabase();
            } catch (Throwable throwable) {
                MLog.error(this, "DBManager CoreDbThread can not get writable database. " + throwable);
            }
        }
    }

    public void uninit() {
        if (mDBHelper != null) {
            mDownloadMusicDao = null;
            mMenuDao = null;
            mPlayListDao = null;
            mRecentSongDao = null;
            mSongDao = null;

            mDBHelper.close();
            mDBHelper = null;
        }
    }


    /**
     * ==============DownloadMusicEntityDao======
     */


    public void insertDownMusicSyn(final DownloadMusicEntity downloadDBEntity) {
        if (mDownloadMusicDao != null) {
            mDownloadMusicDao.insertDownMusicSyn(downloadDBEntity);
        }
        return;
    }

    public boolean updateDownMusic(final DownloadMusicEntity downloadDBEntity) {
        if (mDownloadMusicDao != null) {
            return mDownloadMusicDao.updateDownMusic(downloadDBEntity);
        }
        return false;
    }

    public boolean updateDownMusicList(final List<DownloadMusicEntity> downloadMusicEntityList) {
        if (mDownloadMusicDao != null) {
            return mDownloadMusicDao.updateDownMusicList(downloadMusicEntityList);
        }
        return false;
    }

    public boolean deleteDownMusicByList(final List<Integer> list, boolean deleteFile) {
        if (mDownloadMusicDao != null) {
            return mDownloadMusicDao.deleteDownMusicByList(list, deleteFile);
        }
        return false;

    }

    public boolean isExsitIdSyn(final long downID, int status) {
        if (mDownloadMusicDao != null) {
            return mDownloadMusicDao.isExsitIdSyn(downID, status);
        }
        return false;
    }

    public DownloadMusicEntity getDownMusicByDownloadIdSyn(final long downID) {
        if (mDownloadMusicDao != null) {
            return mDownloadMusicDao.getDownMusicByDownloadIdSyn(downID);
        }
        return null;
    }

    public DownloadMusicEntity getDownMusicByPath(String path) {
        if (mDownloadMusicDao != null) {
            return mDownloadMusicDao.getDownMusicByPath(path);
        }
        return null;
    }

    public List<DownloadMusicEntity> getDownMusicByDownloadStatus(final int downloadStatus) {
        if (mDownloadMusicDao != null) {
            return mDownloadMusicDao.getDownMusicByDownloadStatus(downloadStatus);
        }
        return null;
    }

    public long getDownMusicCount() {
        if (mDownloadMusicDao != null) {
            return mDownloadMusicDao.getDownMusicCount();
        }
        return 0;
    }

    public List<DownloadMusicEntity> getDowningMusic() {
        if (mDownloadMusicDao != null) {
            return mDownloadMusicDao.getDowningMusic();
        }
        return null;
    }

    /**
     * ===============MenuEntityDao ===================
     */

    public boolean insertMenu(final MenuDBEntity menuDBEntity) {
        if (mMenuDao != null) {
            return mMenuDao.insertMenu(menuDBEntity);
        }
        return false;
    }

    public boolean insertMenuList(final List<MenuDBEntity> menuDBEntities) {
        if (mMenuDao != null) {
            return mMenuDao.insertMenuList(menuDBEntities);
        }
        return false;
    }

    public boolean updateMenu(final MenuDBEntity menuDBEntity) {
        if (mMenuDao != null) {
            return mMenuDao.updateMenu(menuDBEntity);
        }
        return false;
    }

    public boolean updateMenuList(final List<MenuDBEntity> menuDBEntities) {
        if (mMenuDao != null) {
            return mMenuDao.updateMenuList(menuDBEntities);
        }
        return false;
    }

    public List<MenuDBEntity> getAllMenuSyn() {
        if (mMenuDao != null) {
            return mMenuDao.getAllMenuSyn();
        }
        return null;
    }

    public boolean isExistIdSyn(final int menuId) {
        if (mMenuDao != null) {
            return mMenuDao.isExistIdSyn(menuId);
        }
        return false;
    }

    public MenuDBEntity getMenuByIdSyn(final int menuId) {
        if (mMenuDao != null) {
            return mMenuDao.getMenuByIdSyn(menuId);
        }
        return null;
    }

    public List<MenuDBEntity> getMenuByEditableSyn(final int editable) {
        if (mMenuDao != null) {
            return mMenuDao.getMenuByEditableSyn(editable);
        }
        return null;
    }


    public long getMenuCount() {
        if (mMenuDao != null) {
            return mMenuDao.getMenuCount();
        }
        return 0;
    }


    public void deleteMenuListByIdSyn(List<Integer> ids) {
        if (mMenuDao != null) {
            mMenuDao.deleteMenuListByIdSyn(ids);
        }
    }

    public void deleteMenuByIdSyn(int id) {
        if (mMenuDao != null) {
            mMenuDao.deleteMenuByIdSyn(id);
        }
    }

    /**
     * PlayListEntityDao
     */
    public void insertSongListSyn(final List<PlayListDBEntity> playListDBEntities) {
        if (mPlayListDao != null) {
            mPlayListDao.insertSongListSyn(playListDBEntities);
        }
    }

    public void clearPlayList() {
        if (mPlayListDao != null) {
            mPlayListDao.clearSongList();
        }
    }


    public void updateSong(final PlayListDBEntity updateSong) {
        if (mPlayListDao != null) {
            mPlayListDao.updateSong(updateSong);
        }
    }

    public void insertPlayList(final PlayListDBEntity updateSong) {
        if (mPlayListDao != null) {
            mPlayListDao.insertPlayList(updateSong);
        }
    }


    public PlayListDBEntity getSongBySongIdSyn(final long songID) {
        if (mPlayListDao != null) {
            return mPlayListDao.getSongBySongIdSyn(songID);
        }
        return null;
    }


    public List<PlayListDBEntity> getAllPlayListSyn() {
        if (mPlayListDao != null) {
            return mPlayListDao.getAllPlayListSyn();
        }
        return null;
    }


    public void deleteSongBySongId(long songID) {
        if (mPlayListDao != null) {
            mPlayListDao.deleteSongBySongId(songID);
        }
    }

    public void deleteSongListByList(List<Music> list) {
        if (mPlayListDao != null) {
            mPlayListDao.deleteSongListByList(list);
        }
    }

    /**
     * RecentSongEntityDao ==========
     */

    public void insertSongSyn(final RecentMusicDBEntity recentEntity) {
        if (mRecentSongDao != null) {
            MLog.info("hzhnex", "insertSongSyn" + recentEntity.lyricsCode);
            mRecentSongDao.insertSongSyn(recentEntity);
        }
    }

    public boolean updateSong(final RecentMusicDBEntity recentEntity) {
        if (mRecentSongDao != null) {
            MLog.info("hzhnex", "updateSong" + recentEntity.lyricsCode);
            return mRecentSongDao.updateSong(recentEntity);
        }
        return false;
    }


    public List<RecentMusicDBEntity> getAllRecent() {
        if (mRecentSongDao != null) {
            return mRecentSongDao.getAllRecent();
        }
        return null;
    }


    public long getRecentCount() {
        if (mRecentSongDao != null) {
            return mRecentSongDao.getRecentCount();
        }
        return 0;
    }


    public void deleteRecentSongList(final List<Integer> idList) {
        if (mRecentSongDao != null) {
            mRecentSongDao.deleteSongListByIdList(idList);
        }
    }

    /**
     * SongEntityDao=====
     */
    public void insertSongList(final List<SongDBEntity> songDBEntities) {
        if (mSongDao != null) {
            mSongDao.insertSongList(songDBEntities);
        }
    }

    public void insertSong(final SongDBEntity songDBEntity) {
        if (mSongDao != null) {
            mSongDao.insertSong(songDBEntity);
        }
    }

    public void updateSong(final SongDBEntity songDBEntity) {
        if (mSongDao != null) {
            mSongDao.updateSong(songDBEntity);
        }
    }

    public void updateSongList(final List<SongDBEntity> songDBEntitys) {
        if (mSongDao != null) {
            mSongDao.updateSongList(songDBEntitys);
        }
    }

    public List<SongDBEntity> getSongByIsLike(final int isLike) {
        if (mSongDao != null) {
            return mSongDao.getSongByIsLike(isLike);
        }
        return null;
    }


    public List<SongDBEntity> getSongListByIdArray(final List<Integer> songIds) {
        if (mSongDao != null) {
            return mSongDao.getSongListByIdArray(songIds);
        }
        return null;
    }


    public SongDBEntity getSongById(final long songID) {
        if (mSongDao != null) {
            return mSongDao.getSongBySongIdSyn(songID);
        }
        return null;
    }


    public String getQtypeBySongIdSyn(final long songID) {
        if (mSongDao != null) {
            return mSongDao.getQtypeBySongIdSyn(songID);
        }
        return "";
    }

    public List<SongDBEntity> getSongLsitBySongIdSyn(final List<Long> songIDList) {
        if (mSongDao != null) {
            return mSongDao.getSongLsitBySongIdSyn(songIDList);
        }
        return null;
    }

    public boolean isExistSongDBId(int songID) {
        if (mSongDao != null) {
            return mSongDao.isExistId(songID);
        }
        return false;
    }
}

